<template>
  <!-- 运力地图 -->
  <div class="demo-spin-article">
    <div style="margin-bottom: 20px">
      <!-- <Input
        v-model="vehicleNums"
        placeholder="输入车牌号"
        style="width: 300px"
      /> -->
      <Select
        transfer
        v-model="vehicleNums"
        filterable
        clearable
        @on-query-change="changeDriver"
        placeholder="输入车牌号"
        style="width: 300px"
      >
        <Option
          v-for="(item, index) in licenseList"
          :key="index"
          :value="item.mapId"
        >
          {{ item.vehicleNum }}
        </Option>
      </Select>
      <Button style="margin-left: 20px" type="primary" @click="mapSearch"
        >搜索</Button
      >
    </div>
    <div class="springFrame">
      <div id="container-map"></div>
      <div
        v-if="cssShow"
        ref="infoData"
        class="custom-info input-card content-window-card"
      >
        <div class="info-top">
          <div>
            <span>车辆定位</span>
            <span style="font-size: 11px; margin-left: 20px; color: #f00"
              >状态：{{
                devInfo.registStatus == "1"
                  ? "已认证"
                  : devInfo.registStatus == "2"
                  ? "待审核"
                  : "已注销"
              }}</span
            >
          </div>
          <img
            @click="closeInfoWindow"
            src="https://webapi.amap.com/images/close2.gif"
          />
        </div>
        <div class="info-middle" style="background-color: white">
          <a class="info-a-title" href="#">{{ devInfo.vehicleNum }}</a>
          <div class="info-a-title">地址：{{ address }}</div>
          <div class="info-div">
            姓名：
            {{ devInfo.driverName }}
          </div>
          <span class="info-span">
            电话：{{ devInfo.driverPhone }}<br />
            <div class="info-div">
              运输中：{{ devInfo.taskState == "0" ? "空闲" : "满载" }}
            </div>
            <span class="info-span">
              装载吨数：{{
                devInfo.goodWeight ? devInfo.goodWeight + " 吨" : "0"
              }}</span
            ><br />
            <div class="info-div">
              车辆类型：{{
                this.$options.filters["TypeGoods"](devInfo.vehicleType)
              }}
            </div>
            <div class="info-div">
              车主电话：{{
                devInfo.contactPhone ? devInfo.contactPhone : "未填写"
              }}
            </div>
            <div class="info-a-title">
              所有人：{{
                devInfo.vehicleOwner ? devInfo.vehicleOwner : "未填写"
              }}
            </div>
          </span>
        </div>
      </div>
    </div>
    <div>
      <div id="container"></div>
    </div>
    <!--  -->
    <div ref="aainfoData" class="licensenumber">
      <div class="info-top"></div>
    </div>
    <!--  -->
    <div class="search-css">
      <Row>
        <Form
          ref="searchForm"
          :model="searchForm"
          inline
          :label-width="68"
          class="search-form"
          style="width: 1680px"
        >
          <FormItem label="查询范围" prop="goodNo">
            <RadioGroup
              v-model="searchForm.Radios"
              @on-change="changeRadioGroup"
            >
              <Radio label="whole">
                <span>全部</span>
              </Radio>
              <Radio label="region">
                <span>根据区域查询</span>
              </Radio>
            </RadioGroup>
          </FormItem>

          <FormItem label="" style="margin-left: -65px">
            <Cascader
              :disabled="searchForm.Radios == 'whole'"
              transfer
              style="width: 200px"
              v-model="searchForm.LoadingAddress"
              :data="LoadingAddresslist"
              :load-data="LoadingProvinceloadData"
              @on-change="getStartArea"
              clearable
            ></Cascader>
          </FormItem>
          <FormItem label="车辆状态">
            <Select
              clearable
              v-model="searchForm.vehicleState"
              style="width: 180px"
              placeholder="请选择车辆状态  "
            >
              <Option value="">全部</Option>
              <Option value="0">空车</Option>
              <Option value="1">满载</Option>
            </Select>
          </FormItem>
          <span style="margin-left: 35px" class="br">
            <Button @click="getDataList" type="primary" icon="ios-search"
              >搜索</Button
            >
            <Button @click="handleReset">重置</Button>
            <Button @click="getDataList" icon="md-refresh">刷新</Button>
          </span>
          <div>
            <div style="display: flex">
              <div></div>
              <div style="margin-left: 10px" class="Check-css">货物类型:</div>
            </div>
            <RadioGroup
              v-model="searchForm.goodsTypaes"
              @on-change="checkAllGroupChange"
            >
              <Radio
                v-for="(item, index) in goodType"
                :key="index"
                :label="item.label"
              >
              </Radio>
            </RadioGroup>
          </div>
          <div style="display: flex">
            <div>
              <div style="display: flex">
                <div style="margin: 10px 0"></div>
                <div style="margin: 10px 0; margin-left: 10px">
                  货物二级分类:
                </div>
              </div>

              <CheckboxGroup
                v-model="searchForm.goodsSubTypaes"
                @on-change="goodsCheckbox"
              >
                <Radio v-model="toSingle" @on-change="toChange">全部</Radio>
                <Checkbox
                  v-for="(item, index) in dangerousList"
                  :key="index"
                  :label="item.description"
                ></Checkbox>
              </CheckboxGroup>
            </div>
          </div>
        </Form>
      </Row>
    </div>
    <!--  -->
    <div class="line"></div>
    <!--  -->
    <Spin size="large" fix v-if="spinShow"></Spin>
  </div>
</template>
<script>
import GPS from "@/libs/GPS";
import {
  vehicleListPosition, // 运力地图 --- 查询车辆位置信息
  getVehicleGpalInfoVo, // 根据设备号获取车辆相关信息
} from "@/api/monitoring";
import { getProvinceData, getAreaCityList, Gaudemap } from "@/api/index";
import iconMap from "@/assets/cak.png";
import excel from "@/libs/excel";

import iconGreen from "@/assets/green.png";
import iconRed from "@/assets/red.png";
export default {
  data() {
    return {
      licenseList: [],
      cssShow: false,
      spinShow: false, //全局加载
      curMapAddress: false, //车辆弹框
      mapVehic: null,
      marker: null,
      caraddress: "",
      carspd: "",
      carVehicle: "",
      carTime: "",
      //
      searchForm: {
        Radios: "whole",
        goodsTypaes: "全部",
        goodsTypae: "",
        goodsSubTypaes: [],
        goodsSubTypae: "",
        vehicleState: "",
        LoadingAddress: "",
        areaCode: "",
      },
      goodsSingle: false, //一级全选
      toSingle: true, //二级全选
      LoadingAddresslist: [],
      goodType: [], //货物类型
      dangerousList: [], //危险品分类
      //
      columns: [
        {
          type: "selection",
          width: 60,
          align: "center",
        },
        {
          title: "#",
          type: "index",
          width: 60,
        },
        {
          title: "姓名",
          key: "name",
          minWidth: 180,
        },
        {
          title: "车牌号",
          key: "license",
          minWidth: 180,
        },
        {
          title: "车辆类型",
          key: "type",
          minWidth: 180,
        },
        {
          title: "核定载质量",
          key: "capacity",
          minWidth: 180,
        },
        {
          title: "联系电话",
          key: "contact",
          minWidth: 180,
        },
        {
          title: "是否运输",
          key: "transport",
          minWidth: 180,
          render: (h, params) => {
            if (params.row.transport == 1) {
              return h("div", "是");
            } else {
              return h("div", { style: { color: "#DC143C" } }, "否");
            }
          },
        },

        {
          title: "操作",
          slot: "actionCarriage",
          align: "center",
          fixed: "right",
          width: 120,
        },
      ],
      data: [],
      //
      settlementData: [],
      shoW: false,
      showApm: true,
      devInfo: {
        title: "",
        icon: "",
        state: "",
        address: "",
        electricity: "",
        gas: "",
        guan: "",
        water: "",
        years: "",
        time: "",
        mianji: "",
      },
      address: "",
      zoomSize: "",
      map: null,

      markerData: [],

      greaterThanMarker: null,
      marker: "",
      vehicleNums: "",
      n: 0,
    };
  },
  mounted() {
    this.getDataList();
    this.goodType = JSON.parse(window.localStorage.getItem("good_type"));
    this.goodType.forEach((item) => {
      item.label = item.description;
      if (item.subList) {
        item.subList.forEach((item2) => {
          item2.label = item2.description;
        });
        item.children = item.subList;
      }
    });
    this.goodType.unshift({
      description: "全部",
      dictId: 10000,
      label: "全部",
      title: "",
      value: "全部",
    });
    this.getProvinceDataList();
  },
  created() {},

  methods: {
    // 驾驶驾驶员输入框编辑
    changeDriver(val) {
      this.licenseList = excel.fuzzySearch(this.markerData, val);
    },
    // 搜索
    mapSearch() {
      let arr = {};
      this.markerData.forEach((item) => {
        if (this.vehicleNums == item.mapId) {
          return (arr = item);
        } else {
          // return (arr = {});
        }
      });
      if (arr.lon) {
        this.map.setCenter([Number(arr.lon), Number(arr.lat)]);
      } else {
        return this.$Message.warning("暂时没有找到这辆车，请重新输入");
      }
    },
    //
    changeRadioGroup(val) {
      if (val == "whole") {
        this.searchForm.LoadingAddress = "";
        this.searchForm.areaCode = "";
      }
    },
    // 重置
    handleReset() {
      this.$refs.searchForm.resetFields();

      this.searchForm.Radios = "whole";
      this.searchForm.goodsTypaes = "";
      this.searchForm.goodsTypae = "";
      this.searchForm.goodsSubTypaes = [];
      this.searchForm.goodsSubTypae = "";
      this.searchForm.LoadingAddress = "";
      this.searchForm.areaCode = "";
      this.getDataList();
    },
    // 地图车辆
    getDataList() {
      this.spinShow = true;
      if (this.searchForm.LoadingAddress.length == 0) {
        this.searchForm.areaCode = "";
      }
      if (this.searchForm.Radios == "whole") {
        this.searchForm.areaCode = "";
      }
      let arr = [];
      if (this.searchForm.goodsSubTypaes) {
        this.dangerousList.forEach((item) => {
          this.searchForm.goodsSubTypaes.forEach((e) => {
            if (item.description == e) {
              arr.push(item.value);
            }
          });
        });
        this.searchForm.goodsSubTypae = arr.join(",");
      } else {
        this.searchForm.goodsSubTypae = "";
      }

      this.loading = true;
      for (let item in this.searchForm) {
        if (!this.searchForm[item]) {
          delete this.searchForm[item];
        }
      }
      let longitude = [113.307718, 33.735241];
      vehicleListPosition(this.searchForm).then((res) => {
        this.spinShow = false;
        if (res.code == 200) {
          this.markerData = res.result;
          this.map = this.createMap(longitude);
          this.map.clearMap();
          this.addMarker();
        } else {
          this.$Message.error(res.message);
          this.map = this.createMap(longitude);
          this.map.clearMap();
          this.addMarker();
        }
      });
    },
    // 货物类型全选
    radioChange(val) {
      if (val) {
        this.searchForm.goodsTypae = "";
        this.searchForm.goodsSubTypaes = [];
        this.searchForm.goodsSubTypae = [];
        this.toSingle = true;
        this.dangerousList = [];
      }
    },
    // 货物类型
    checkAllGroupChange(val) {
      if (val == "全部") {
        return this.radioChange(true);
      }
      this.searchForm.goodsSubTypaes = [];
      this.searchForm.goodsSubTypae = "";
      this.goodType.forEach((item) => {
        if (item.label == val) {
          this.searchForm.goodsTypae = item.value;
          axios.get("/freight/dictData/getByType/" + item.title).then((res) => {
            if (res.success) {
              this.dangerousList = res.result;
            }
          });
        }
      });
    },
    // 货物二级分类 全选
    toChange(val) {
      if (val) {
        this.searchForm.goodsSubTypaes = [];
        this.searchForm.goodsSubTypae = [];
      }
    },
    // 货物二级分类
    goodsCheckbox(val) {
      this.toSingle = false;
    },
    // 获取卸货省份数据
    getProvinceDataList() {
      let fn = () => {
        getProvinceData().then((res) => {
          if (res.code == 200) {
            res.result.forEach(function (e) {
              e.level = 1;
              e.label = e.provinceName;
              e.pid = e.provinceCode;
              e.value = e.provinceCode;
              e.loading = false;
              e.children = [];
            });
            this.LoadingAddresslist = res.result;
            // this.loadingData = res.result;
          } else {
            this.$Message.error(res.message);
          }
        });
      };
      fn();
    },
    // 选择装货地址
    getStartArea(value, selectedData) {
      if (selectedData.length == 3) {
        this.searchForm.areaCode = value[2]; //搜索赋值
      }
    },
    //搜索装货详细地址
    LoadingProvinceloadData(item, callback) {
      this.$nextTick(() => {
        item.loading = true;
        getAreaCityList({ code: item.value, type: item.level }).then((res) => {
          item.loading = false;
          if (res.code == 200) {
            res.result.forEach(function (e) {
              if (e.level != 3) {
                e.level = e.level;
                e.label = e.label;
                e.pid = e.pid;
                e.value = e.value;
                e.loading = false;
                e.children = [];
              } else {
                e.value = e.value;
                e.label = e.label;
              }
            });
            item.children = res.result;
            callback();
          } else {
            this.$Message.error(res.message);
          }
        });
      });
    },
    // 调度
    dispatchClick(row) {
      this.$router.push({
        name: "goods-map",
        query: {
          key: row,
          map: 1,
        },
      });
    },
    mapShow(val) {
      let startx = val.lon;
      let starty = val.lat;
      var map = new AMap.Map("themap", {
        resizeEnable: true,
        // center: val[0],
        center: [val.lon, val.lat],
        zoom: 13,
      });
      var begin = new AMap.Marker({
        position: new AMap.LngLat(startx, starty), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        icon: "https://webapi.amap.com/images/car.png",
      });
      map.add(begin);
      // marker1.setMap(map);
    },
    //1.创建map对象
    createMap(longitude) {
      let this_ = this;
      //1.地图初始化时，在地图上添加marker标记,鼠标点击marker可弹出自定义的信息窗体
      var mapData = new AMap.Map("container-map", {
        resizeEnable: true,
        zoom: 8,
        center: longitude, //地图中心点位置
      });
      return mapData;
    },

    //2.添加点标记
    addMarker() {
      const this_ = this;
      let arr = [];

      // 注意传递的经纬度坐标要是数值型
      this.markerData.forEach((item) => {
        item.mark = GPS.gcj_encrypt(Number(item.lat), Number(item.lon));
      });
      this.markerData.forEach((item) => {
        this_.n++;
        let marker1 = new AMap.Marker({
          position: [item.mark.lon, item.mark.lat], //位置
          offset: new AMap.Pixel(-3, -30), //偏移
          icon: new AMap.Icon({
            image: item.taskState == "0" ? iconGreen : iconRed,
            size: new AMap.Size(52, 52), //图标大小
            imageSize: new AMap.Size(35, 35),
          }),
        });
        // 0......................
        // 初始化坐标点自定义窗口
        this.aainitInfoWindow(item.mark.lon, item.mark.lat);
        marker1.setLabel({
          offset: new AMap.Pixel(0, 0),
          content: this.aacreateInfoWindow(item),
          direction: "bottom",
        });
        marker1.setMap(this.map);
        // 0......................
        arr.push(
          Object.assign(item, {
            mapId: marker1._amap_id,
          })
        );
        marker1.setMap(this_.map);

        AMap.event.addListener(marker1, "click", (e) => {
          this_.markerClick(arr, marker1);
        });
      });
      // // 清除
      //   if (this_.map) {
      //     this_.map.clearMap();
      //   }
    },

    // 初始化信息窗体
    aainitInfoWindow(lng, lat, item) {
      // console.log('创建了信息窗体')
      this.infoWindow = new AMap.InfoWindow({
        isCustom: false, //使用自定义窗体
        anchor: "bottom-center",
        content: "",
        offset: new AMap.Pixel(0, -20),
        autoMove: true,
        closeWhenClickMap: false,
      });
    },
    // 创建信息窗体
    aacreateInfoWindow(item) {
      if (this.n < this.markerData.length - 1) {
      }
      return `
      <div class="dn-info-window">
          <div class="dn-info-num">${item.vehicleNum}</div>
        </div>
      `;
    },
    //3.点击标记 获取所点击标记的信息以及窗体要展示的数据，创建信息窗体
    markerClick(arr, marker) {
      this.cssShow = true;

      let arrNew = arr.filter((x) => x.mapId == marker._amap_id);

      getVehicleGpalInfoVo({ gpsEquipment: arrNew[0].gpsEquipment }).then(
        (res) => {
          if (res.code == 200) {
            this.devInfo = res.result;
            axios
              .get(
                "https://restapi.amap.com/v3/geocode/regeo?location=" +
                  [arrNew[0].mark.lon, arrNew[0].mark.lat] +
                  "&key=" +
                  Gaudemap +
                  "&batch=" +
                  true +
                  " "
              )
              .then((res) => {
                this.address = res.regeocodes[0].formatted_address;
                let infoWindow = this.createInfoWindow();
                this.openInfoWindow(infoWindow, marker);
              });
          } else {
            this.$Message.error(res.message);
          }
        }
      );
      // this.devInfo = arrNew && arrNew[0];
    },
    //4.构建自定义窗体
    createInfoWindow() {
      let infoWindowData = new AMap.InfoWindow({
        isCustom: true, //使用自定义窗体
        content: this.$refs.infoData,
        // content: this.getContent(),
        offset: new AMap.Pixel(16, -45),
      });
      return infoWindowData;
    },

    //5.打开窗体
    openInfoWindow(infoWindow, marker) {
      infoWindow.open(this.map, marker.getPosition());
    },
    //6.关闭窗体
    closeInfoWindow() {
      this.map.clearInfoWindow();
    },
  },
};
</script>

<style>
html,
body,
#container-map {
  height: 800px;
  width: 100%;
}
.content-window-card {
  position: relative;
  box-shadow: none;
  bottom: 0;
  left: 0;
  /* width: auto; */
  width: 28rem;
  padding: 0;
}

.content-window-card p {
  height: 2rem;
}

.custom-info {
  border: solid 1px silver;
}

div.info-top {
  position: relative;
  background: none repeat scroll 0 0 #f9f9f9;
  border-bottom: 1px solid #ccc;
  border-radius: 5px 5px 0 0;
}

div.info-top div {
  display: inline-block;
  color: #333333;
  font-size: 14px;
  font-weight: bold;
  line-height: 31px;
  padding: 0 10px;
}

div.info-top img {
  position: absolute;
  top: 10px;
  right: 10px;
  transition-duration: 0.25s;
}

div.info-top img:hover {
  box-shadow: 0px 0px 5px #000;
}

div.info-middle {
  font-size: 12px;
  padding: 10px 6px;
  line-height: 20px;
}

div.info-bottom {
  height: 0px;
  width: 100%;
  clear: both;
  text-align: center;
}

div.info-bottom img {
  position: relative;
  z-index: 104;
}

/* span {
  margin-left: 5px;
  font-size: 11px;
} */

.info-middle img {
  float: left;
  margin-right: 6px;
}

.info-span {
  margin: 5px 0;
  font-size: 14px;
}

.info-div {
  width: 200px;
  display: inline-block;
  margin-left: 10px;
  font-size: 14px;
}

.info-img {
  width: 40px;
  height: 40px;
}

.info-a-title {
  /* color: #000000; */
  font-size: 14px;
  margin: 5px 0;
  margin-left: 10px;
}
#container-map {
  height: 820px;
}
/* #container .amap-icon img,
.amap-marker-content img {
  width: 64px;
  height: 64px;
} */
.springFrame {
  height: 650x;
  width: 95%;
  overflow: hidden;
}
/* 第二层 */
/* <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css"/> */

.collision-btn.disable {
  background-image: none;
  color: lightgrey;
  border-color: lightgrey;
  cursor: not-allowed;
}
.collision-btn.disable:hover {
  background-color: #fff;
  border-color: lightgrey;
}
.input-card .btn {
  margin-right: 0.8rem;
}
.title {
  position: absolute;
  top: 0;
  left: 50%;
  padding: 0.5em 1em;
  height: auto;
  border-radius: 2px;
  font-weight: 500;
  font-size: 20px;
  width: 307px;
  margin-left: -153px;
  text-align: center;
}
</style>
<style lang="less" scoped>
.search-css {
  margin-top: 20px;
  margin-left: 10px;
}
.Check-css {
  margin-bottom: 10px;
}
.line {
  margin: 20px 0;
  border: 1px solid #eee;
}
.but-css {
  background-color: white;
  display: flex;
  justify-content: flex-end;
  padding: 8px;
}
.licensenumber {
  width: 50px;
  height: 50px;
}

// 自定义窗体的样式
/deep/.info-window {
  padding: 10px;
  // background: rgba(4, 77, 145, 0.753);
  color: red !important;
  border-radius: 10px;
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  -ms-border-radius: 10px;
  -o-border-radius: 10px;

  .info-name {
    font-size: 16px;
    font-family: PingFang SC;
    font-weight: 800;
    color: red !important;
  }

  .info-num {
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #a5a3a1;

    > span {
      font-size: 14px;
      color: #3196fa;

      &.active-color {
        color: #ef4864;
      }
    }
  }
}
// @import url("https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css");
</style>